package com.kingtao.rpc;

import com.kingtao.message.*;
import com.kingtao.protocol.MessageCodec;
import com.kingtao.protocol.ProtocolFrameDecoder;
import com.kingtao.util.CoreData;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Scanner;

/**
 * @Author: kingtao
 * @Date: 2023-08-25-15:20
 * @Description:
 */
@Slf4j
public class client {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);

        MessageCodec CODEC_HANDLER = new MessageCodec();
        try {
            Bootstrap client = new Bootstrap();
            client.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new ProtocolFrameDecoder());
                            channel.pipeline().addLast(LOGGING_HANDLER);
                            channel.pipeline().addLast(CODEC_HANDLER);
                            channel.pipeline().addLast("server init", new ChannelInboundHandlerAdapter() {

                                //  接收消息
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    log.debug("msg: {}", msg);
                                }

                                //  触发连接后建立
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    //  控制台输入
                                    new Thread(() -> {
                                        Scanner scanner = new Scanner(System.in);
                                        System.out.println("server 初始数量：");
                                        String line = scanner.nextLine();
                                        //  构造消息对象
                                        ServerInitRequest serverInitRequest = new ServerInitRequest(Integer.parseInt(line));
                                        log.debug( "{}",serverInitRequest);
                                        ctx.writeAndFlush(serverInitRequest);
                                        while (true) {
                                            System.out.println("---------------");
                                            System.out.println("1、发送请求");
                                            System.out.println("2、leader宕机");
                                            System.out.println("3、新增节点");
                                            System.out.println("4、开启分组");
                                            System.out.println("---------------");
                                            String s = scanner.nextLine();
                                            switch (s){
                                                case "1":
                                                    System.out.println("输入请求内容：");
                                                    String str = scanner.nextLine();
                                                    ClientRequest clientRequest = new ClientRequest(str);
                                                    ctx.writeAndFlush(clientRequest);
                                                    break;
                                                case "2":
                                                    SelectLeaderRequest leaderRequest = new SelectLeaderRequest(0);
                                                    ctx.writeAndFlush(leaderRequest);
                                                    break;
                                                case "3":
                                                    System.out.println("输入新增节点数目：");
                                                    String num = scanner.nextLine();
                                                    AppendNodeRequest request = new AppendNodeRequest(Integer.parseInt(num));
                                                    ctx.writeAndFlush(request);
                                                    break;
                                                case "4":
                                                    System.out.println("默认分组数目：" + CoreData.GROUP_NUM);
                                                    SelectFollowerLeaderRequest request1 = new SelectFollowerLeaderRequest();
                                                    ctx.writeAndFlush(request1);
                                                    break;
                                            }
                                        }
                                    }, "system in").start();
                                }

                            });
                            channel.pipeline().addLast(new SimpleChannelInboundHandler<HeartBeatResponse>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HeartBeatResponse heartBeatResponse) throws Exception {
                                    if (heartBeatResponse.isLeaderSuccess() == false) {
                                        SelectLeaderRequest leaderRequest = new SelectLeaderRequest(0);
                                        ctx.writeAndFlush(leaderRequest);
                                    }
                                    else if (heartBeatResponse.isSecondLeaderSuccess() == false) {
                                        SelectSecondLeaderRequest selectSecondLeaderRequest = new SelectSecondLeaderRequest();
                                        ctx.writeAndFlush(selectSecondLeaderRequest);
                                    }
                                    else {
                                        log.debug("集群的leader与secondLeader状态没有改变");
                                    }
                                }
                            });
                        }
                    });
            ChannelFuture future = client.connect("127.0.0.1", CoreData.NODE_INIT_PORT);
            Channel channel = future.sync().channel();

            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.debug("{}", e.getMessage());
        } finally {
            group.shutdownGracefully();
        }


    }
}
